<template>
  <div p-5>
    <DynamicTable
      bordered
      :data-request="loadData"
      :columns="columns"
      row-key="id"
      @resize-column="handleResizeColumn"
      :scroll="{
        y: 'calc(100vh - 360px)',
      }"
    >
      <template #toolbar>
        <a-button type="primary" @click="openUserModal({})"> 新增 </a-button>
      </template>
    </DynamicTable>

    <a-modal
      v-model:open="open"
      title="查看详情"
      :width="800"
      :footer="null"
      :destroyOnClose="true"
    >
      <a-descriptions bordered>
        <a-descriptions-item label="机构名称" :span="2">{{ selectItem.name }}</a-descriptions-item>
        <a-descriptions-item label="机构类型" :span="2">{{ selectItem.type }}</a-descriptions-item>
        <a-descriptions-item label="机构简称" :span="2">{{
          selectItem.shortName
        }}</a-descriptions-item>
        <a-descriptions-item label="机构地址" :span="2">{{
          selectItem.address
        }}</a-descriptions-item>
        <a-descriptions-item label="备注" :span="4">{{
          selectItem.remark || '暂无备注'
        }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
  import { ref } from 'vue';
  import { Modal, message } from 'ant-design-vue';
  import { baseColumns, type TableListItem } from './columns';
  import { userSchemas } from './formSchemas';

  import {
    getTableListApi,
    updateDept,
    createDept,
    getDetailOragn,
    deleteDeptApi,
  } from '@/api/system/oragn/index';
  import { getDictory, getAreaList } from '@/api/account/index';

  import {
    useTable,
    type OnChangeCallbackParams,
    type TableColumn,
  } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/index';

  const [showModal] = useFormModal();

  const [DynamicTable, dynamicTableInstance] = useTable();
  const columns: TableColumn[] = [
    ...baseColumns,
    {
      title: '操作',
      align: 'left',
      width: 140,
      dataIndex: 'ACTION',
      actions: ({ record }) => [
        {
          label: '查看',
          onClick: () => openInfoMoadl(record),
        },
        {
          ifShow: record.dataType === 2,
          label: '编辑',
          onClick: () => openUserModal(record),
        },
        {
          ifShow: record.dataType === 2,
          label: '删除',
          onClick: () => deleteDept(record),
        },
      ],
    },
  ];

  const loadData = async (
    params,
    onChangeParams: OnChangeCallbackParams,
  ): Promise<API.TableListResult> => {
    const data = await getTableListApi(params);
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list: data,
          ...params,
        });
      }, 500);
    });
  };

  const handleResizeColumn = (w, col) => {
    col.width = w;
  };

  /**
   * @description 打开机构弹窗
   */
  const openUserModal = async (record: Partial<TableListItem> = {}) => {
    const [formRef] = await showModal<any>({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}机构`,
        width: 700,
        onFinish: async (values) => {
          values.id = record.id;
          await (record.id ? updateDept : createDept)(values);
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 80,
        schemas: userSchemas,
        autoSubmitOnEnter: true,
      },
    });

    getDictory('dept_type').then((res) => {
      formRef?.updateSchema([
        {
          field: 'typeId',
          componentProps: ({ formModel, formInstance }) => {
            return {
              options: res,
              fieldNames: { label: 'configName', value: 'id' },
              onChange: (value: string, option) => {
                formModel.type = option.configName;
              },
            };
          },
        },
      ]);
    });
    getAreaList().then((res) => {
      formRef?.updateSchema([
        {
          field: 'address',
          componentProps: ({ formModel, formInstance }) => {
            return {
              options: res,
              fieldNames: { label: 'name', value: 'id', children: 'children' },
              onChange: (value: string, option) => {
                formModel.cityCode = option[0].id;
                formModel.city = option[0].name;
                formModel.countyCode = option[1].id;
                formModel.county = option[1].name;
                formModel.townCode = option[2].id;
                formModel.town = option[2].name;
              },
            };
          },
        },
      ]);
    });

    // formRef?.setFieldsValue(record);
    if (record?.id) {
      const data = await getDetailOragn(record.id);
      data.address = [data.cityCode, data.countyCode, data.townCode];
      formRef?.setFieldsValue(data);
    }
  };

  /**
   * @description 删除机构
   */
  const deleteDept = (record: Partial<TableListItem> = {}) => {
    Modal.confirm({
      title: '确定删除该机构？',
      centered: true,
      onOk: async () => {
        await deleteDeptApi(record.id);
        dynamicTableInstance?.reload?.();
      },
      onCancel: () => {},
    });
  };

  const open = ref(false);
  const selectItem = ref<Partial<TableListItem>>({});
  const openInfoMoadl = (record) => {
    open.value = true;
    selectItem.value = record;
  };
</script>
<style scoped lang="less"></style>
